package com.director.core.json.impl.gson;

import com.director.core.DirectAction;
import com.director.core.DirectMethod;
import com.director.core.RemotingProvider;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Type;

/**
 * @author Simone Ricciardi
 * @version 1.0, 10/31/2011
 */
public class RemotingProviderTypeAdapter implements JsonSerializer<RemotingProvider> {

   @Override
   public JsonElement serialize(RemotingProvider src, Type typeOfSrc, JsonSerializationContext context) {

      JsonObject jsonProvider = new JsonObject();
      jsonProvider.addProperty("id", src.getId());
      jsonProvider.addProperty("url", src.getUrl());
      jsonProvider.addProperty("type", src.getType());
      if(StringUtils.isNotBlank(src.getNamespace())) {
         jsonProvider.addProperty("namespace", src.getNamespace());
      }

      JsonObject jsonActions = new JsonObject();
      for(DirectAction directAction : src.getActions()) {
         JsonArray jsonMethods = new JsonArray();
         for(DirectMethod directMethod : directAction.getMethods()) {
            JsonObject jsonMethod = new JsonObject();
            jsonMethod.addProperty("name", directMethod.getName());
            jsonMethod.addProperty("len", directMethod.getLen());
            jsonMethod.addProperty("formHandler", directMethod.isFormHandler());
            jsonMethods.add(jsonMethod);
         }
         jsonActions.add(directAction.getName(), jsonMethods);
      }

      jsonProvider.add("actions", jsonActions);
      return jsonProvider;
   }
}
